package com.shangma.cn.components;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.shangma.cn.common.domin.LoginAdmin;
import com.shangma.cn.common.exception.ApiException;
import com.shangma.cn.common.http.AxiosStatus;
import com.shangma.cn.entity.Admin;
import com.shangma.cn.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 开发者：辉哥
 * 特点： 辉哥很帅
 * 开发时间：2021/7/1 16:26
 * 文件说明：
 */
@Component
public class TokenService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public static final String secret = "ajghghhhh";


    public String createTokenAndCacheLoginAdmin(Admin admin) {
        String s = UUID.randomUUID().toString();
        LoginAdmin loginAdmin = new LoginAdmin();
        loginAdmin.setUuid(s);
        loginAdmin.setAdmin(admin);
        setLoginAdminCache(loginAdmin);
        return createToken(s);
    }


    /**
     * 缓存登录用户
     *
     * @param loginAdmin
     */
    public void setLoginAdminCache(LoginAdmin loginAdmin) {
        stringRedisTemplate.opsForValue().set(loginAdmin.getUuid(), JsonUtils.obj2Str(loginAdmin));
    }

    /**
     * 生成Token
     */

    public String createToken(String uuid) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        String token = JWT.create()
                .withIssuer("辉哥") //设置签发者
                .withSubject("登录token")
                .withClaim("uuid", uuid)
                .sign(algorithm);
        return token;
    }

    /**
     * 解析Token
     * 解析失败时 会有异常
     */
    public DecodedJWT verifyToken(HttpServletRequest httpServletRequest) {
        String authentication = httpServletRequest.getHeader("Authentication");
        String token = authentication.split(" ")[1];
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer("辉哥") //设置签发者
                .withSubject("登录token")
                .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        return jwt;
    }

    /**
     * 获得token中uuid
     */
    public String getUUId() {
        DecodedJWT decodedJWT = verifyToken(getRequest());
        String uuid = decodedJWT.getClaim("uuid").asString();
        return uuid;
    }


    public LoginAdmin getLoginAdminCache() {
        String uuId = getUUId();
        String s = stringRedisTemplate.opsForValue().get(uuId);
        LoginAdmin loginAdmin = JsonUtils.str2Obj(s, LoginAdmin.class);
        return loginAdmin;
    }

    public Long adminId() {
        Long id = getLoginAdminCache().getAdmin().getId();
        return id;
    }

    public boolean isAdmin(HttpServletRequest request) {
        return getLoginAdminCache().getAdmin().getIsAdmin();
    }

    /**
     * 判断token是否准确
     *
     * @param httpServletRequest
     * @return
     */
    public boolean checkTokenIsSure(HttpServletRequest httpServletRequest) {
        String authentication = httpServletRequest.getHeader("Authentication");
        //没有传递Token
        if (StringUtils.isEmpty(authentication)) {
            throw new ApiException(AxiosStatus.NO_LOGIN);
        }
        //token没有携带前缀 格式不正确
        if (!authentication.startsWith("Bearer ")) {
            throw new ApiException(AxiosStatus.NO_LOGIN);
        }
        //格式也不对
        String[] s = authentication.split(" ");
        if (s.length != 2) {
            throw new ApiException(AxiosStatus.NO_LOGIN);
        }
        //如果解析出现异常 表示Token正确
        try {
            verifyToken(httpServletRequest);
        } catch (Exception e) {
            throw new ApiException(AxiosStatus.NO_LOGIN);
        }

        return true;
    }


    /**
     * 获取全局的Request
     */

    public HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        System.out.println("request对象是=" + request);
        return request;
    }

    /**
     * 获取全局的Response
     */

    public HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

}
